#include "RayTracer/Shapes/Sphere.hpp"
#include "RayTracer/ParseTypes.hpp"


using namespace RayTracer;


Sphere::Sphere()
:	mPosition( Vector3::Zero() )
,	mRadius( 1.0f )
{
}


bool Sphere::Parse( Scene& s, JSONValue* v )
{
	if( !::Parse( v, "Position", mPosition ) )
		return false;

	if( !::Parse( v, "Radius", mRadius ) )
		return false;

	return Model::Parse( s, v );
}


bool Sphere::Intersect( Vector3::ParamType_t origin, Vector3::ParamType_t dir, float& t ) const
{
	Vector3		dist	=	mPosition - Vector3( origin );
	float		B		=	Vector3( dir ) * dist;
	float		D		=	B*B - dist*dist + mRadius*mRadius;

	if( D < 0.0f )
		return false;

	float	t0	=	B - std::sqrt( D );
	float	t1	=	B + std::sqrt( D );

	bool retvalue = false;

	if( (t0 > 0.0f) && (t0 < t) )
	{
		t			=	t0;
		retvalue	=	true;
	}
	if( (t1 > 0.0f) && (t1 < t) )
	{
		t = t1;
		retvalue = true;
	}
	return retvalue;
}


Vector3 Sphere::Normal( const Vector3& hp ) const
{
	Vector3	result( hp - mPosition );
	result.Normalize();
	return result;
}
